package com.sskj.login.ui.activity;


import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.gyf.barlibrary.ImmersionBar;
import com.hey.lib.HeySpinner;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.sskj.common.base.HttpData;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.enums.AreaCodeEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.box.verifier.ToastNextInputs;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CaptchaUtil;
import com.sskj.lib.util.EditUtil;
import com.sskj.lib.util.SchemeUtil;
import com.sskj.lib.util.SendCodeUtil;
import com.sskj.login.R;
import com.sskj.login.R2;
import com.sskj.login.bean.LoginBean;
import com.sskj.login.component.DaggerUserDataComponent;
import com.sskj.login.presenter.LoginActivityPresenter;
import com.sskj.login.util.TipLoginUtil;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 登录
 */
@Route(path = RConfig.LOGIN_LOGIN)
public class LoginActivity extends BaseActivity<LoginActivityPresenter> {
    @BindView(R2.id.tvRegister)
    TextView tvRegister;
    @BindView(R2.id.etAccount)
    EditText etAccount;
    @BindView(R2.id.etPwd)
    EditText etPwd;
    @BindView(R2.id.btLogin)
    Button btLogin;
    @BindView(R2.id.tvPwdForget)
    TextView tvPwdForget;
    @BindView(R2.id.ivPwdToggle)
    ImageView ivPwdToggle;


    private AndroidNextInputs inputs;
    @Inject
    UserViewModel userViewModel;
    private MaterialDialog googleCheckDialog;
    private AreaCodeEnum areaCodeEnumChoose;
    @BindView(R2.id.heySpinner)
    HeySpinner heySpinner;

    @Override
    protected int getLayoutId() {
        ImmersionBar.with(this).statusBarColor(R.color.lib_dominant).statusBarDarkFont(false).init();
        return R.layout.login_activity_login;
    }


    @Override
    public LoginActivityPresenter getPresenter() {
        return new LoginActivityPresenter();
    }

    @Override
    protected void initView() {
        DaggerUserDataComponent.create().inject(this);
        ClickUtil.click(tvRegister, () -> {
            ARouter.getInstance().build(RConfig.LOGIN_REGISTER).navigation();
        });
        inputs = new ToastNextInputs();

        inputs.clear();
        inputs.add(etAccount, SchemeUtil.notEmpty(etAccount), SchemeUtil.emailPhone())
                .add(etPwd, SchemeUtil.notEmpty(etPwd), SchemeUtil.pwd());


        ClickUtil.click(btLogin, () -> {
            if (inputs.test()) {
                mPresenter.login(areaCodeEnumChoose.getAreaCode(), etAccount.getText().toString(), etPwd.getText().toString(), "APP");
            }
        });

        EditUtil.togglePs(etPwd, ivPwdToggle);

        ClickUtil.click(tvPwdForget, () -> {
            ARouter.getInstance().build(RConfig.LOGIN_PWD_FORGET).navigation();
        });

        LiveDataBus.get().with(RxBusCode.REGISTER_ACCOUNT, String.class)
                .observe(this, account -> {
                    if (etAccount != null && account != null) {
                        etAccount.setText(account);
                    }
                });
        heySpinner.setVisibility(Constans.isAreaCode ? View.VISIBLE : View.GONE);
        SendCodeUtil.areaCode(this, heySpinner, areaCodeEnum -> {
            areaCodeEnumChoose = areaCodeEnum;
        });

    }

    public void loginSuccess(LoginBean data) {
        CaptchaUtil.check(this, (result, validate, msg) -> {
            saveDataAndLogin(data);
            mPresenter.sendLoginSms(etAccount.getText().toString(), data.getId(), data.getToken());
        });
    }

    public void saveDataAndLogin(LoginBean data) {

        OkGo.<HttpData<Map<String, String>>>get(BaseHttpConfig.BASE_URL + "/app/user/getSysConfig")
                .execute(new JsonCallBack<HttpData<Map<String, String>>>() {
                    @Override
                    public void onSuccess(Response<HttpData<Map<String, String>>> response) {
                        HttpData<Map<String, String>> httpData = response.body();
                        String huilv = httpData.getData().get("usdtToRmbRate");
                        String bibNum = httpData.getData().get("bibNum");
                        String forceNum = httpData.getData().get("forceNum");
                        SPUtil.put(SPConfig.HUILV, huilv);
                        SPUtil.put(SPConfig.BIBNUM, bibNum);
                        SPUtil.put(SPConfig.FORCENUM, forceNum);
                        Constans.HUILV = huilv;
                    }
                });
        HttpHeaders httpHeaders = OkGo.getInstance().getCommonHeaders();
        HttpParams httpParams = OkGo.getInstance().getCommonParams();
        httpHeaders.put(SPConfig.TOKEN, data.getToken());
        httpHeaders.put(SPConfig.HEADER_ID, data.getId());
        httpParams.put(SPConfig.ID, data.getId());
        httpParams.put(SPConfig.STOCK_USER_ID, data.getId());
        SPUtil.put(SPConfig.ID, data.getId());
        SPUtil.put(SPConfig.USER_ACCOUNT, etAccount.getText().toString());
        SPUtil.put(SPConfig.TOKEN, data.getToken());
        SPUtil.put(SPConfig.MOBILE, etAccount.getText().toString());
        SPUtil.put(SPConfig.GOOGLETYPE, data.getIsGoogleAuthentication());
        SPUtil.put(SPConfig.LOGIN, true);
        SPUtil.put(SPConfig.AREA_CODE, areaCodeEnumChoose.getAreaCode());

        userViewModel.update();
        finish();
        overridePendingTransition(R.anim.lib_anim_out, R.anim.lib_anim_back);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.lib_anim_out, R.anim.lib_anim_back);

    }

    public void googleCheck(LoginBean loginBean) {
        CaptchaUtil.check(this, (result, validate, msg) -> {
            AndroidSchedulers.mainThread().scheduleDirect(() -> {
                googleCheckDialog = TipLoginUtil.showGoogleCheckDialog(LoginActivity.this, pwd -> {
                    googleCheckDialog.dismiss();
                    mPresenter.checkGoogle(pwd, loginBean);
                });
                googleCheckDialog.show();
            });
        });
    }

    public void checkSuccess(LoginBean data) {
        saveDataAndLogin(data);
        mPresenter.sendLoginSms(etAccount.getText().toString(), data.getId(), data.getToken());
    }
}
